<template>
  <div>
    <!-- 按钮 -->

    <el-button style="margin:10px 10px" type="primary" icon="el-icon-refresh-right" circle
      @click="getDynamicExtensionProcessList"></el-button>
    <el-button type="primary" @click="add()">添加</el-button>
    <el-table style="width: 100%;" border :data="list">
      <!-- <el-table-column prop="createId" label="名称" align="center">
        </el-table-column> -->
      <!--     <el-table-column prop="isHotQuestion" label="热门" align="center">
        <template slot-scope="{ row, $index }">
          <div>{{ row.isHotQuestion == "0" ? '热门' : '非热门' }}</div>
        </template>
      </el-table-column> -->


      <el-table-column prop="title" label="标题" align="center">
      </el-table-column>
      <el-table-column prop="content" label="内容" align="center">
      </el-table-column>
      <el-table-column label="新闻动态图片" align="center" width="150">
        <template slot-scope="{ row, $index }">
          <img :src="$staticURL+row.picUrl" style=" width:40px; height:40px" />
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" align="center">
      </el-table-column>
      <!--      <el-table-column prop="iconUrl" label="分类图标" align="center">
      </el-table-column> -->

      <!--      <el-table-column prop="costMoney" label="消费金额" align="center">
            </el-table-column> -->

      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="{ row, $index }">
          <!-- <el-button type="primary" icon="el-icon-edit" circle></el-button> -->
          <el-tooltip content="修改" placement="top" slot="reference">
            <el-button type="primary" icon="el-icon-edit" @click="ubpateBannar(row)"></el-button>
          </el-tooltip>
          <el-popconfirm title="是否删除？" icon="el-icon-info" icon-color="red" @confirm="getDelete(row.id)">
            <el-tooltip content="删除" placement="top" slot="reference">
              <el-button type="danger" icon="el-icon-delete"></el-button>
            </el-tooltip>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination style="margin-top:20px;textAlign:center" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :current-page="pageNumber" :page-sizes="[10, 50, 100]" :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!-- 修改对话框  -->
    <el-dialog title="修改" :visible.sync="dialogFormVisible">
      <el-form style="width:80%" :model="tmFrom" :rules="rules" ref="ruleForm">
        <!--      <el-form-item label="会员等级" label-width="100px" prop="memberLevel">
                    <div>{{ tmFrom.memberLevel == 1 ? "vip" : "Svip" }}</div>
                </el-form-item> -->
        <!--  <el-form-item label="问题名称" label-width="100px" prop="sortName">
          <el-input autocomplete="off" v-model="tmFrom.sortName"></el-input>
        </el-form-item> -->

        <!-- <el-form-item label="热门" label-width="100px">
          <el-select v-model="tmFrom.isHotQuestion" placeholder="请选择是否自定义" prop="isHotQuestion">
            <el-option label="热门" value="0"></el-option>
            <el-option label="非热门" value="1"></el-option>
          </el-select>
        </el-form-item> -->


        <el-form-item label="标题" label-width="100px" prop="title">
          <el-input autocomplete="off" v-model="tmFrom.title"></el-input>
        </el-form-item>

        <el-form-item label="内容" label-width="100px" prop="content">
          <el-input autocomplete="off" v-model="tmFrom.content"></el-input>
        </el-form-item>


        <el-form-item label='新闻动态图片' label-width="100px">
          <el-upload class="avatar-uploader" action='#' :on-preview="handlePictureCardPreview" :on-change="uploadFile"
            :auto-upload="false" :show-file-list='false'>

            <i v-if="imageUrl1" class="el-icon-circle-close " @click.stop="handleRemove1"></i>
            <i v-if="imageUrl1" class="el-icon-zoom-in " @click.stop="handlePictureCardPreview"></i>


            <img v-if='imageUrl1' :src='imageUrl1' class='avatar' :show-file-list='false'>
            <i v-else class='el-icon-plus avatar-uploader-icon'></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
            <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
          </el-dialog>
        </el-form-item>

        <!-- <el-form-item label='图标' label-width="100px">
          <el-upload class="avatar-uploader" drag action="#" :show-file-list="false" :auto-upload="false"
            :on-change="uploadFile" accept="image/jpg,image/jpeg,image/png">
            <i v-if="imageUrl1" class="el-icon-circle-close deleteImg" @click.stop="handleRemove1"></i>
            <img v-if="imageUrl1" :src="imageUrl1" class="avatar" />

            <div v-else>
              <i class="el-icon-picture" style="margin-top: 40px; font-size: 40px; color: #999a9c"></i>
              <div class="el-upload__text1">上传图片</div>
                   <div class="el-upload__text">* 建议尺寸比例1，不超过4m，</div>
            <div class="el-upload__text">格式为png、jpeg或jpg</div>
            </div>
          </el-upload>
        </el-form-item> -->

        <!-- <el-form-item label="消费金额" label-width="100px" prop="costMoney">
                    <el-input autocomplete="off" v-model="tmFrom.costMoney"></el-input>
                </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="getAddBannerImage" v-if="state">确 定</el-button>
        <el-button type="primary" @click="UpdateBillingRules" v-else>修改</el-button>
      </div>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog title="添加新闻" :visible.sync="dialogFormVisible1">
      <el-form style="width:80%" :model="list1" :rules="rules" ref="ruleForm">
        <!--   <el-form-item label="热门" label-width="100px">
          <el-select v-model="list1.isHotQuestion" placeholder="请选择是否自定义" prop="memberLevel">
            <el-option label="热门" value="0"></el-option>
            <el-option label="非热门" value="1"></el-option>
          </el-select>
        </el-form-item> -->

        <!--    <el-form-item label="会员类型">
          <el-select v-model="list1.memberLevelName" placeholder="请选择是否自定义" prop="memberLevelName">
            <el-option label="月卡" value="月卡"></el-option>
            <el-option label="季卡" value="季卡"></el-option>
            <el-option label="年卡" value="年卡"></el-option>
          </el-select>
        </el-form-item> -->


        <el-form-item label="标题" label-width="100px" prop="title">
          <el-input autocomplete="off" v-model="list1.title"></el-input>
        </el-form-item>

        <el-form-item label="内容" label-width="100px" prop="content">
          <el-input autocomplete="off" v-model="list1.content"></el-input>
        </el-form-item>


        <el-form-item label='新闻动态图片' label-width="100px">
          <el-upload class="avatar-uploader" action='#' :on-preview="handlePictureCardPreview" :on-change="uploadFile"
            :auto-upload="false" :show-file-list='false'>

            <i v-if="imageUrl1" class="el-icon-circle-close " @click.stop="handleRemove1"></i>
            <i v-if="imageUrl1" class="el-icon-zoom-in " @click.stop="handlePictureCardPreview"></i>


            <img v-if='imageUrl1' :src='imageUrl1' class='avatar' :show-file-list='false'>
            <i v-else class='el-icon-plus avatar-uploader-icon'></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
            <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
          </el-dialog>
        </el-form-item>

        <!--  <el-form-item label='图标' label-width="100px">
          <el-upload class="avatar-uploader" drag action="#" :show-file-list="false" :auto-upload="false"
            :on-change="uploadFile" accept="image/jpg,image/jpeg,image/png">
            <i v-if="imageUrl1" class="el-icon-circle-close deleteImg" @click.stop="handleRemove1"></i>
            <img v-if="imageUrl1" :src="imageUrl1" class="avatar" />

            <div v-else>
              <i class="el-icon-picture" style="margin-top: 40px; font-size: 40px; color: #999a9c"></i>
              <div class="el-upload__text1">上传图片</div>
                   <div class="el-upload__text">* 建议尺寸比例1，不超过4m，</div>
            <div class="el-upload__text">格式为png、jpeg或jpg</div>
            </div>
          </el-upload>
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="aa(list1.id)">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import axios from 'axios'
  import {
    getToken
  } from '@/utils/auth'
  export default {
    name: 'memorabiliaQGS',
    data() {

      return {

        //页码
        pageNumber: 1,
        //每页数量
        pageSize: 10,
        //总条数
        total: 0,


        formData: '',
        imageUrl1: '',
        imageUrl: '',
        dialogVisible: false,
        dialogImageUrl: '',
        dialogImageName: '',
        //列表数据
        list: [],
        list1: {
          // logoUrl: '',
          type: 2,
          // iconUrl: '',
          // costMoney: "",
          // memberLevel: "",
          // memberLevelName: "",
          // monthNum: ""
        },
        // 对话框显示与隐藏控制
        dialogFormVisible: false,
        dialogFormVisible1: false,
        // 表单对象
        tmFrom: {
          // logoUrl: '',
          type: 2,
        },
        // 当前为修改还是添加 修改为false 添加为true
        state: true,
        // 表单验证
        rules: {
          // name: [
          //     { required: true, message: '请输入规则名称', trigger: 'blur' }
          // ],
          // proportion: [
          //     { required: true, message: '请选择计费比列，数字和小数', trigger: 'blur' },
          //     {
          //         transform(value) {
          //             return Number(value);
          //         },
          //         validator(rule, value, callback) {
          //             if (Number.isFinite(value) && value > 0) {
          //                 callback();
          //             } else {
          //                 callback(new Error("请输入类型为数字和小数，并不少于0"));
          //             }
          //         },
          //         trigger: "blur",
          //     }
          // ],
          // intro: [
          //     { required: true, message: '请选择规则简介', trigger: 'blur' }
          // ]
        }

      }
    },
    mounted() {
      this.getDynamicNewsList()
    },
    // computed: {
    //   headers() {
    //     return {
    //       'session_token': getToken()
    //     };
    //   }
    // },

    methods: {

      uploadFile(item) {
        console.log(item);
        let formData = new FormData();
        let file = item.raw;
        // this.file = item.raw;
        this.imageUrl1 = URL.createObjectURL(file);
        formData.append("image", file);
        this.formData = formData
        console.log(file, "216")
        // console.log(formData.get('file'))

        // console.log(formData.get('file'))

        // let res = this.$API.question.uploadImgage({
        //   image: formData
        // })
        // 传formData给后台就行
        // 比如
        // 接口(formData).then(res=>{
        // this.videoUrl=res.url
        // })
      },
      aa() {
        /* console.log(this.list1)
          return false; */
        axios({
          method: "post",
          url: "https://api.yushiai.com.cn/biz/uploadImgage",
          data: this.formData,
          headers: {
            'session_token': getToken(),
            'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryLOZf2MbOw2wkMpjv'
          },
        }).then((res) => {
          console.log(res)
          if (res.data.code == 200) {
            console.log(res.data.data.imgageUrl)
            this.list1.picUrl = res.data.data.imgageUrl
            console.log(this.list1)
            this.$refs.ruleForm.validate(async (valid) => {
              if (valid) {
                let res = await this.$API.webQGS.addDynamicNews(this.list1);
                this.dialogFormVisible1 = false;
                this.getDynamicNewsList()
                this.list1 = ''
                this.imageUrl1 = ""
              } else {
                console.log('error submit!!');
                return false;
              }
            })
          }
        })
        // let res = this.$API.question.uploadImgage({
        //   image: this.formData
        // })
        // console.log(res)
      },
      // 删除只需清空imageUrl1即可
      handleRemove1(file, fileList) {
        // console.log(file, fileList);
        this.imageUrl1 = "";
      },
      // 预览
      handlePictureCardPreview(file) {
        this.dialogImageUrl = this.imageUrl1;
        this.dialogVisible = true;
      },

      // handleSuccess(res, file, fileList) {
      //   this.imageUrl = URL.createObjectURL(file.raw)
      // },
      // beforeUpload(file) {
      //   console.log(file)
      //   let size = file.size
      //   let type = file.type
      //   let kb = 1024
      //   let isLt15KB = size / 1024 / 15 <= 1
      //   let isPNG = type === "image/png"
      //   if (!isPNG) {
      //     this.$message.error('上传头像格式错误，应该为PNG');
      //   }
      //   if (!isLt15KB) {
      //     this.$message.error('上传头像大小不能超过15KB')
      //   }
      //   console.log(size / 1024 / 15)
      //   return isPNG && isLt15KB
      // },


      // 获取产品/大事记分页列表
      async getDynamicNewsList() {
        let res = await this.$API.webQGS.getDynamicNewsList({
          pageNumber: this.pageNumber,
          pageSize: this.pageSize,
          orderBY: ''
        })
        console.log(res, "大事记分页列表")

        this.list = res.data.rows;
        this.total = res.data.sumLine;

        // const arr = [];
        // for (let i = 0; i < res.data.rows.length; i++) {
        //   if (res.data.rows[i].type == 2) {
        //     arr.push(res.data.rows[i])
        //   }
        // }
        // console.log(arr, "大事记分页列表arr")
        // this.list = arr;
        // this.total = arr.length;
      },

      // 取消
      getShow() {
        this.state = true
        this.dialogFormVisible = true
        this.tmFrom = {
          // logoUrl: '',
          type: 2,
          // name: '',
          // proportion: '',
          // intro: ''
        }
      },

      add() {
        this.dialogFormVisible1 = true
      },
      // 刷新
      getDynamicExtensionProcessList() {
        this.getDynamicNewsList()
      },
      // 添加
      getAddBannerImage() {
        console.log(this.addQuestionSort());
      },
      // 添加一条会员套餐
      addQuestionSort() {
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            let res = await this.$API.question.addDynamicNews(this.list1);
            this.dialogFormVisible1 = false;
            this.getQuestionSortList()
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },

      // 点击修改
      ubpateBannar(row) {
        this.state = false
        this.dialogFormVisible = true;
        // 浅拷贝  让tmFrom收到的数据非服务器直接传回的数据
        this.tmFrom = {
          ...row
        };
      },
      // 点击修改
      UpdateBillingRules() {
        this.tmFrom.type = 2
        if (this.imageUrl1 == "") {
          this.$refs.ruleForm.validate(async (valid) => {
            if (valid) {
              let res = await this.$API.webQGS.updateDynamicNews(this.tmFrom);
              this.dialogFormVisible = false;
              this.getDynamicNewsList()
            } else {
              console.log('error submit!!');
              return false;
            }
          })
        } else {
          axios({
            method: "post",
            url: "https://api.yushiai.com.cn/biz/uploadImgage",
            data: this.formData,
            headers: {
              'session_token': getToken(),
              'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryLOZf2MbOw2wkMpjv'
            },
          }).then((res) => {
            console.log(res)
            if (res.data.code == 200) {
              console.log(res.data.data.imgageUrl)
              this.tmFrom.picUrl = res.data.data.imgageUrl
              console.log(this.tmFrom)
              this.$refs.ruleForm.validate(async (valid) => {
                if (valid) {
                  let res = await this.$API.webQGS.updateDynamicNews(this.tmFrom);
                  this.dialogFormVisible = false;
                  this.getDynamicNewsList()
                  this.list1 = ''
                  this.imageUrl1 = ""
                } else {
                  console.log('error submit!!');
                  return false;
                }
              })
            }
          })
        }

        // console.log(this.tmFrom)
        // this.$refs.ruleForm.validate(async (valid) => {
        //   if (valid) {
        //     let res = await this.$API.question.updateQuestionSort(this.tmFrom);
        //     this.dialogFormVisible = false;
        //     this.getQuestionSortList()
        //   } else {
        //     console.log('error submit!!');
        //     return false;
        //   }
        // })
      },
      // 删除
      async getDelete(id) {
        let res = await this.$API.webQGS.deleteDynamicNews({
          id: id
        });
        this.getDynamicNewsList()

      },

      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val
        this.getDynamicNewsList()

      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.pageNumber = val
        this.getDynamicNewsList()
      },
    }
  }
</script>

<style lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
